package cn.lanqiao.web.utils;


import cn.lanqiao.common.entity.Admin;
import cn.lanqiao.common.entity.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

public class JwtUtils {
    // token时效：24小时
    //public static final long EXPIRE = 1000 * 60 * 60 * 24;
    public static final long EXPIRE = 1000 * 60 * 10;
    // 签名哈希的密钥，对于不同的加密算法来说含义不同
    public static final String APP_SECRET = "ukc8BDbRigUDaY6pZFfWus2jZWLPHO";

    /**
     * 根据用户id和昵称生成token
     * @param username 用户昵称
     * @return JWT规则生成的token
     */
    public static String getJwtToken(String username){
        String JwtToken = Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                .setSubject("lanqiao")
                .setIssuedAt(new Date())
                //.setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .claim("username", username)
                // HS256算法实际上就是MD5加盐值，此时APP_SECRET就代表盐值
                .signWith(SignatureAlgorithm.HS256, APP_SECRET)
                .compact();

        return JwtToken;
    }

    public static String getJwtToken(User user) throws JsonProcessingException {
        if(user == null) return null;
        ObjectMapper objectMapper = new ObjectMapper() ;
        String json = objectMapper.writeValueAsString(user);//把user对象转变为json字符串
        String JwtToken = Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                .setSubject("lanqiao")
                .setIssuedAt(new Date())
                //.setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .claim("user", json)
                // HS256算法实际上就是MD5加盐值，此时APP_SECRET就代表盐值
                .signWith(SignatureAlgorithm.HS256, APP_SECRET)
                .compact();

        return JwtToken;
    }

    public static String getJwtToken(Admin admin) throws JsonProcessingException {
        if(admin == null) return null;
        ObjectMapper objectMapper = new ObjectMapper() ;
        String json = objectMapper.writeValueAsString(admin);//把admin对象转变为json字符串
        String JwtToken = Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                .setSubject("lanqiao")
                .setIssuedAt(new Date())
                //.setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .claim("admin", json)
                // HS256算法实际上就是MD5加盐值，此时APP_SECRET就代表盐值
                .signWith(SignatureAlgorithm.HS256, APP_SECRET)
                .compact();

        return JwtToken;
    }

    /**
     * 判断token是否存在与有效
     * @param jwtToken token字符串
     * @return 如果token有效返回true，否则返回false
     */
    public static boolean checkToken(String jwtToken) {
        if(StringUtils.isEmpty(jwtToken)) return false;
        try {
            Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 判断token是否存在与有效
     * @param request Http请求对象
     * @return 如果token有效返回true，否则返回false
     */
    public static boolean checkToken(HttpServletRequest request) {
        // 从http请求头中获取token字符串
        String jwtToken = request.getHeader("token");

        return checkToken(jwtToken);
    }

    /**
     * 根据token获取会员id
     * @param request Http请求对象
     * @return 解析token后获得的用户id
     */
    public static String getUsernameByJwtToken(HttpServletRequest request) {
        String jwtToken = request.getHeader("token");

        return getUsernameByJwtToken(jwtToken);
    }
    public static String getUsernameByJwtToken(String token) {
        if(StringUtils.isEmpty(token)) return "";
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        return (String)claims.get("username");
    }

    public static User  getUserByJwtToken(String token) throws JsonProcessingException {
        if(StringUtils.isEmpty(token)) return null;
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        String json = (String) claims.get("user") ;
        ObjectMapper objectMapper = new ObjectMapper( );

        User user = objectMapper.readValue(json,User.class) ;
        return user ;
    }

    public static Admin getAdminByJwtToken(String token) throws JsonProcessingException {
        if(StringUtils.isEmpty(token)) return null;
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        String json = (String) claims.get("admin") ;
        ObjectMapper objectMapper = new ObjectMapper( );

        Admin admin = objectMapper.readValue(json,Admin.class) ;
        return admin ;
    }

    public static User getUserByJwtToken(HttpServletRequest request) throws JsonProcessingException {
        String jwtToken = request.getHeader("token") ;
        if(StringUtils.isEmpty(jwtToken)) return null;

        return  getUserByJwtToken(jwtToken) ;
    }

    public static Admin getAdminByJwtToken(HttpServletRequest request) throws JsonProcessingException {
        String jwtToken = request.getHeader("token") ;
        if(StringUtils.isEmpty(jwtToken)) return null;

        return  getAdminByJwtToken(jwtToken) ;
    }

    //刷新token
    public static String refreshToken(String token){
        //获取token的过期时间
        //检查它是不是快过期了
        //如果快过期了，那么就重新生成一个 new_token

        return "new_token" ;
    }
}

